<template>
  <div class="edit-user">
    <div class="main-head flex-between container-fluid">
      <div class="title">
        <h1>{{pageTitle}}</h1>
      </div>
    </div>
    <div class="content container-fluid">
      <div class="breadcrumb" v-if="$route.path.includes('admin')">
        <a-breadcrumb :routes="routes">
          <template slot="itemRender" slot-scope="{route, params, routes}">
            <span v-if="routes.indexOf(route) === routes.length - 1">
              {{type}}
              {{route.breadcrumbName}}
              {{userId ? ` #${userId}` : ''}}
            </span>
            <router-link v-else :to="route.path">{{route.breadcrumbName}}</router-link>
          </template>
        </a-breadcrumb>
      </div>
      <div class="portlet">
        <a-spin :spinning="loading" :delay="delayTime">
          <a-form
            layout="vertical"
            :class="{'includes-photo-item':isOneSelf}"
            :form="form"
            @submit="handleSubmit"
          >
            <div class="conditions grid">
              <!-- Basic Personal Info -->
              <div class="grid-item">
                <div class="grid-item-title">
                  <h3 v-text="$t('pro.admin.BasicInfo')"></h3>
                </div>
                <div class="grid-item-main">
                  <!--邮箱 新增用户或普通用户才显示-->
                  <a-form-item :label="$t('pro.loginReg.loginPla')" v-if="isAdminAdd || isOneSelf">
                    <a-input
                            :disabled="!isAdminAdd"
                            v-decorator="[
                        'user.email',
                          {
                            rules: [{
                              type: 'email', message: $t('pro.loginReg.loginWra'),
                            }, {
                              required: true, message: $t('pro.loginReg.loginMessage'),
                            }]
                          }
                    ]"
                    />
                  </a-form-item>

                  <!--姓-->
                  <a-form-item :label="$t('pro.loginReg.RegFirst')">
                    <span slot="label">
                      First Name&nbsp;
                      <a-tooltip :title="$t('pro.admin.callyou')">
                        <a-icon type="question-circle-o" />
                      </a-tooltip>
                    </span>
                    <a-input
                      v-decorator="[
                      'user.firstName',
                      {
                        rules: [{
                          required: true, message: $t('pro.loginReg.RegFirName'), whitespace: true
                        }, {
                          validator: validateToName
                        }]
                      }
                    ]"
                    />
                  </a-form-item>
                  <!--名-->
                  <a-form-item :label="$t('pro.loginReg.Reglast')">
                    <span slot="label">
                      Last Name
                      <a-tooltip :title="$t('pro.admin.callyou')">
                        <a-icon type="question-circle-o" />
                      </a-tooltip>
                    </span>
                    <a-input
                      v-decorator="['user.lastName',
                          {
                            rules: [{
                              required: true, message: $t('pro.loginReg.ReLastName'), whitespace: true
                            }, {
                              validator: validateToName
                            }]
                          }
                        ]"
                    />
                  </a-form-item>

                  <!--密码-->
                  <a-form-item :label="$t('pro.loginReg.passwordPla')" v-if="isAdminAdd">
                    <a-input
                      v-decorator="[
                        'user.passwordDigest',
                        {
                          rules: [{
                            required: true, message:$t('pro.loginReg.passwordMess'),
                          }, {
                            validator: validateToPassword,
                          }],
                        }
                      ]"
                      type="password"
                    />
                  </a-form-item>

                  <!--角色-->
                  <a-form-item :label="$t('pro.admin.role')" v-if="!isOneSelf">
                    <a-select v-decorator="['user.roleId',{initialValue: 2}]" :disabled="isOneSelf">
                      <a-select-option :value="1">{{$t('pro.admin.Admin')}}</a-select-option>
                      <a-select-option :value="2">{{$t('pro.admin.User')}}</a-select-option>
                    </a-select>
                  </a-form-item>

                  <!-- ssp选项 -->
                  <a-form-item :label="$t('pro.admin.ssp')" v-if="!isOneSelf">
                    <a-select
                            :placeholder="$t('pro.admin.ssp1')"
                            mode="multiple"
                            allowClear
                            :filterOption="filterOption"
                            v-decorator="['user.ssp']">
                      <a-select-option :value="item.id+''" v-for="item in sspList" :key="item.id">{{item.name}}</a-select-option>
                    </a-select>
                  </a-form-item>

                  <!-- 功能组 -->
                  <a-form-item v-if="!isOneSelf">
                    <a-row>
                      <a-col :span="12">
                        <a-switch v-decorator="['user.prepay', { valuePropName: 'checked' }]" />
                        <span class="dsp-form-text" :style="{ color: styleBC }">{{ actions[0]}}</span>
                      </a-col>
                      <a-col :span="12">
                        <a-switch v-decorator="['user.isActive', { valuePropName: 'checked' }]" />
                        <span class="dsp-form-text" :style="{ color: styleBC }">{{ actions[1]}}</span>
                      </a-col>
                      <!-- 查看真实SSP名称 -->
                      <!-- <a-col :span="12">
                           <a-switch v-decorator="['user.canSeeSsp', { valuePropName: 'checked' }]"/>
                           <span class="dsp-form-text" :style="{ color: styleBC }">
                              {{ actions[2]}}
                           </span>
                      </a-col>-->
                      <a-col :span="12">
                        <a-switch v-decorator="['user.autoAprove', { valuePropName: 'checked' }]" />
                        <span class="dsp-form-text" :style="{ color: styleBC }">{{ actions[3]}}</span>
                      </a-col>
                    </a-row>
                  </a-form-item>
                </div>
              </div>

              <!-- Contact Info -->
              <div class="grid-item">
                <div class="grid-item-title">
                  <h3 v-text="$t('pro.admin.ContactInfo')"></h3>
                </div>
                <div class="grid-item-main">
                  <!--国家-->
                  <a-form-item :label="$t('pro.admin.Country')">
                    <a-select
                      mode="tag"
                      style="width: 100%"
                      :tokenSeparators="[',']"
                      :placeholder="$t('pro.loginReg.Country')"
                      :showSearch="true"
                      v-decorator="[
                            'user.country',
                            {
                              rules: [{ required: true, message: $t('pro.loginReg.CountryMess'), whitespace: true }]
                            }
                        ]"
                    >
                      <a-select-option
                        v-for="countriesOption in countriesOptions"
                        :key="countriesOption.id"
                        :value="countriesOption.commonName"
                      >{{ countriesOption.commonName }}</a-select-option>
                    </a-select>
                  </a-form-item>

                  <!--公司-->
                  <a-form-item :label="$t('pro.admin.Company')">
                    <a-input
                      v-decorator="[
                        'user.company',
                        {
                          rules: [{ required: true, message: $t('pro.loginReg.CompanyMess'), whitespace: true }]
                        }
                      ]"
                    />
                  </a-form-item>

                  <!--手机号-->
                  <!--
                       {
                        rules: [{
                          required: true, message: $t('pro.loginReg.PhoneMess')
                        }, {
                          validator: validateToPhoneNumber
                        }],
                      }
                  -->
                  <a-form-item :label="$t('pro.admin.Phone')">
                    <a-input
                      v-decorator="['user.phone',{
                        rules: [{
                            required: true, message: $t('pro.loginReg.PhoneMess')
                          }, {
                            validator: validateToPhoneNumber,
                          }],
                      }]"
                      style="width: 100%"
                    >
                      <a-select
                        class="select-phone"
                        slot="addonBefore"
                        v-decorator="['user.telephoneCode',{ initialValue: '86' }]"
                        style="width: 70px"
                      >
                        <a-select-option
                          v-for="telephoneCodeOption in telephoneCodeOptions"
                          :key="telephoneCodeOption.ituTTelephoneCode"
                          :value="telephoneCodeOption.ituTTelephoneCode"
                        >{{ telephoneCodeOption.ituTTelephoneCode }}</a-select-option>
                      </a-select>
                    </a-input>
                  </a-form-item>
                  <!--地址-->
                  <a-form-item :label="$t('pro.admin.Address')">
                    <a-input v-decorator="[
                        'user.address']" />
                  </a-form-item>
                </div>
              </div>

              <!-- 修改 邮箱 密码 （只要添加用户不出现） -->
              <div class="grid-item" v-if="!isAdminAdd">
                <div class="grid-item-title" style="border-bottom: 1px solid #c2cad8;">
                  <h3 v-text="$t('pro.public.userIDSet')"></h3>
                </div>
                <div class="grid-item-main">
                  <!--邮箱-->
                  <a-form-item v-if="!isOneSelf">
                    <span slot="label">
                      {{ $t('pro.loginReg.loginPla') }}&nbsp;
                      <a-tooltip :title="$t('pro.loginReg.titleEmail')">
                        <a-icon type="question-circle-o" />
                      </a-tooltip>
                    </span>
                    <a-input-search
                      type="email"
                      v-model="adminEmail"
                      @search="adminEditEmail"
                      class="dsp-emal-edit"
                    >
                      <a-button
                        type="primary"
                        slot="enterButton"
                        icon="edit"
                      >{{$t('pro.public.buttonYes')}}</a-button>
                    </a-input-search>
                  </a-form-item>

                  <!--密码-->
                  <a-form-item>
                    <span slot="label">
                      {{ $t('pro.loginReg.passwordUpdate') }}&nbsp;
                      <a-tooltip :title="$t('pro.loginReg.titlePwd')">
                        <a-icon type="question-circle-o" />
                      </a-tooltip>
                    </span>
                    <a-input-search type="password" @search="swidthEditPwd" class="dsp-pwd-edit">
                      <a-button
                        type="primary"
                        slot="enterButton"
                        icon="edit"
                      >{{$t('pro.public.buttonYes')}}</a-button>
                    </a-input-search>
                  </a-form-item>
                </div>
              </div>
            </div>
            <!--按钮-->
            <div class="grid-item grid-submit-item">
              <a-form-item>
                <a-button
                  type="primary"
                  html-type="submit"
                  :disabled="loading"
                  v-text="$t('pro.admin.Submit')"
                  style="margin-right: 15px"
                ></a-button>
                <!--<a-button  v-if="!isOneSelf" type="danger" html-type="submit" :disabled="loading" v-text="$t('pro.Editcampaigns.Del')"></a-button>-->
              </a-form-item>
            </div>
          </a-form>
        </a-spin>
      </div>
    </div>
  </div>
</template>

<script>
import {
  addUser,
  modifyById,
  userUpdate,
  getSysUser,
  getUser,
  updateUserPwd
} from "../../api/user";
import { getAllSSP } from '../../api/SSP'
import { sysModifyInfo } from "../../api/sys-user-controller";
import { vPassword, vUserName, vEmail } from "../../utils/validate";

export default {
  inject: ["reload"],
  data() {
    return {
      loading: false,
      delayTime: 500,
      confirmDirty: false,
      form: this.$form.createForm(this),
      autoCompleteResult: [],
      tailFormItemLayout: {
        wrapperCol: {
          xs: {
            span: 24,
            offset: 0
          },
          sm: {
            span: 16,
            offset: 8
          }
        }
      },
      fileName: [],
      countriesOptions: [], //国家
      telephoneCodeOptions: [], //电话前几位书
      adminEmail: "",

        sspList: [],
    };
  },
  computed: {
    styleBC() {
      return this.$store.getters.switchBackColor;
    },
    userId() {
      return this.$route.params.id;
    },
    isOneSelf() {
      return (
        this.userInfo.id === this.userId ||
        this.$route.path === "/bidder/profile"
      );
    },
    //发送是管理添加
    isAdminAdd() {
      return this.userId == null && !this.isOneSelf;
    },
    userInfo() {
      return this.$store.getters.userInfo || { id: "" };
    },
    type() {
      return this.userId ? this.$t("pro.admin.Edit") : this.$t("pro.admin.Add");
    },
    pageTitle() {
      return this.isOneSelf
        ? this.$t("pro.admin.UserProfile")
        : `${this.type} ` + this.$t("pro.admin.User");
    },
    routes() {
      const router = [
        {
          path: "/admin/users",
          breadcrumbName: this.$t("pro.admin.ManageUsers")
        },
        {
          path: "second",
          breadcrumbName: this.$t("pro.admin.User")
        }
      ];
      return router;
    },

    actions() {
      return this.$t("pro.admin.userRole");
    },

    // getEZ(){
    //   routes 1
    // }

    getMapLang() {
      return this.$i18n.locale;
    }
  },
  watch: {
    getMapLang(newVal) {
      this.reload();
    }
  },
  methods: {
      //搜索
      filterOption(input, option) {
          return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },

    //判断是哪个页面修改密码
    swidthEditPwd(pass) {
      if (!!pass && pass.length > 0) {
        if (vPassword(pass)) {
          let ths = this;
          this.$confirm({
            title: `${ths.$t("pro.loginReg.okTitle")}${ths.$t(
              "pro.loginReg.passwordPla"
            )}?`,
            content: `${ths.$t("pro.loginReg.okEd")}`,
            onOk() {
              if (!ths.isOneSelf) {
                ths.adminEditPwd(pass);
              } else {
                ths.userEditPwo(pass);
              }
            },
            onCancel() {}
          });
        } else {
          this.$message.error(this.$t("pro.loginReg.passwordWra"));
        }
      }
    },

    //普通用户修改密码
    userEditPwo(pass) {
      updateUserPwd(pass).then(res => {
        console.log(res.data);
        let { code, data } = res.data || "";
        if (code == 200) {
          if (!!data) {
            this.$message
              .success(this.$t("pro.admin.message.actionOk"))
              .then(() => {
                window.localStorage.clear();
                window.sessionStorage.removeItem("Authorization");
                this.$router.push({
                  path: "/login",
                  query: {
                    lastPath: this.$route.path
                  }
                });
              });
          } else {
            this.$message.warning(
              this.$t("pro.admin.status")[1].value || "success"
            );
          }
        }
      });
    },

    //管理员通用修改密码||邮箱
    adminEditEmailAndPWd(params) {
      return sysModifyInfo(params).then(res => {
        console.log(res.data);
        let { code, data } = res.data || "";
        if (code == 200) {
          if (!!data) {
            //查询管理员是否修改自己信息
            if (this.userInfo.id === this.userId) {
              this.$message
                .success(this.$t("pro.admin.message.actionOk"))
                .then(() => {
                  window.localStorage.clear();
                  window.sessionStorage.removeItem("Authorization");
                  this.$router.push({
                    path: "/login",
                    query: { lastPath: this.$route.path }
                  });
                });
            } else {
              this.$message.success(
                this.$t("pro.Editcampaigns.operationSuccess")
              );
              return true;
            }
          } else {
            this.$message.warning(
              this.$t("pro.admin.status")[1].value || "success"
            );
            return false;
          }
        }
      });
    },

    adminEditEmail(email) {
      if (vEmail(email)) {
        this.adminEditEmailAndPWd({
          email,
          id: this.userId
        }).then(isGet => {
          //管理员修改成功刷新数据
          if (isGet) {
            this.init();
          }
        });
      } else {
        this.$message.error(this.$t("pro.loginReg.loginWra"));
      }
    },

    //管理员修改密码
    adminEditPwd(pass) {
      this.adminEditEmailAndPWd({ pass, id: this.userId });
    },

    //判断管理修改账户安全字段是否重新登录
    submitSuccess(res, isPush) {
      let { code } = res.data;
      if (code == 200) {
        this.$message
          .success(this.$t("pro.Editcampaigns.operationSuccess"))
          .then(() => {
            //判断是不是本人修改自己的 修改自己则重新登录
            if (isPush) {
              this.$router.push("/admin/users");
            }
            // else {
            //   window.localStorage.clear();
            //   window.sessionStorage.removeItem("Authorization");
            //   this.$router.push({
            //     path: "/login",
            //     query: {
            //       lastPath: this.$route.path
            //     }
            //   });
            // }
          });
      }
    },

    adminParams(values) {
      values.user.autoAprove = +values.user.autoAprove;
      values.user.canSeeSsp = +values.user.canSeeSsp;
      values.user.prepay = +values.user.prepay;
      values.user.isActive = +values.user.isActive;
      return values;
    },

    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFieldsAndScroll((err, values) => {
        console.log("问题");
        if (!err) {
          this.loading = true;

          if (this.userId == null && !this.isOneSelf) {
            //Add 管理员
            values = this.adminParams(values);
            // 添加用户
            addUser(values.user)
              .then(res => {
                //刷新缓存
                this.$store.dispatch("GetUserByCompany");
                this.submitSuccess(res, true);
              })
              .catch(e => {
                console.log(e);
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            if (this.userId != null) {
              values.user.id = this.userId;
            }
            //判断是否管理修改
            if (!this.isOneSelf) {
              //管理员修改用户
              values = this.adminParams(values);
              modifyById(values.user)
                .then(res => {
                  this.submitSuccess(res, true);
                })
                .finally(() => {
                  this.loading = false;
                });
            } else {
              //普通用户修改用户
              userUpdate(values.user)
                .then(res => {
                  this.submitSuccess(res, false);
                })
                .finally(() => {
                  this.loading = false;
                });
            }
          }
        }
      });
    },

    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },

    beforeUpload(file) {
      return false;
    },

    handlePhotoChange({ fileList }) {
      this.fileName = fileList;
      console.log(this.fileName);
    },

    validateToName(rule, value, callback) {
      if (value) {
        if (vUserName(value)) {
          callback();
        } else {
          callback(this.$t("pro.loginReg.RegValidate"));
        }
      } else {
        callback("");
      }
    },

    validateToPassword(rule, value, callback) {
      if (value) {
        if (vPassword(value)) {
          callback();
        } else {
          callback(this.$t("pro.loginReg.passwordWra"));
        }
      } else {
        callback("");
      }
    },

    validateToPhoneNumber(rule, value, callback) {
      const pattern = /^[0-9]*$/;
      if (value) {
        if (pattern.test(value)) {
          callback();
        } else {
          callback(this.$t("pro.loginReg.PhoneVali"));
        }
      } else {
        callback("");
      }
    },

    //res 是API返回的数据
    formFomat(res) {
      this.form = this.$form.createForm(this, {
        // 把 props 转为对应的值，可用于把 Redux store 中的值读出,可以在此给form赋值
        mapPropsToFields: () => {
          const obj = res.data.data;
          if (!obj) return;
          let data = {};
          data.user = {};
          for (let [key, value] of Object.entries(obj)) {
            if (value == null) continue;
            if (
              key === "autoAprove" ||
              key === "canSeeSsp" ||
              key === "prepay" ||
              key === "isActive"
            ) {
              value = !!value; //将 1|0 转为 true|false
            }
            if (key === "email") {
              this.adminEmail = value;
            }
            if (key === 'ssp' && !!value) {
                value = value.split(',');
            }
            data.user[key] = this.$form.createFormField({ value: value });
          }

          /* 头像 */
          /*if (obj.fileName) {
                    this.fileName = [
                        {
                            uid: "-1",
                            name: "fileName.png",
                            status: "done",
                            url: obj.fileName
                        }
                    ];
                }*/
          return data;
        }
      });
    },

    //数据刷新初始化
    init() {
      if (this.userId || this.isOneSelf) {
        let parameter = "/" + this.userId;

        if (this.isOneSelf) {
            parameter = "";
            getUser().then(res => {
              this.formFomat(res);
            });

        } else {
            //管理员
            getSysUser(parameter).then(res => {
              this.formFomat(res);
            });

            getAllSSP().then(res => {
                this.sspList = [];
                let { data, code } = res.data || {}
                if (code == 200 && !!data) {
                    data.map(item => {
                        let params = {
                            id: item.id,
                            name: `${item.region}[${item.name}]`
                        };
                        this.sspList.push(params);
                    })
                }
            })

        }
      }
    }
  },

  mounted() {
    this.init();
    this.$store.dispatch("GetCountries").then(res => {
      this.countriesOptions = res;
    });
    this.$store.dispatch("getTelephoneCodeOptions").then(res => {
      this.telephoneCodeOptions = res;
    });
  }
};
</script>

<style scoped>
h2 {
  text-align: center;
}
.dsp-form-text {
  display: inline-block;
  margin-left: 10px;
}
</style>

<style lang="less">
#app.dark .select-phone .ant-select-selection-selected-value {
  color: #888 !important;
}
</style>
